package com.bridgetree.jubaocrm.ui.project;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Process;
import android.preference.PreferenceManager;
import android.support.v4.util.LruCache;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageCache;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.ui.Contents;
import com.bridgetree.jubaocrm.ui.LoginUtil;
import com.bridgetree.jubaocrm.ui.ProgressDialogUtil;
import com.bridgetree.jubaocrm.ui.widget.PullToRefreshBase.OnRefreshListener;
import com.bridgetree.jubaocrm.ui.widget.PullToRefreshListView;
import com.bridgetree.jubaocrm.util.FileInfo;
import com.bridgetree.jubaocrm.util.LoginError;
import com.bridgetree.jubaocrm.util.Projects;
/**
 * 文档资料
 */
public class XMChildDocumentationActivity extends Activity {
	private final String TAG = "XMChildDocumentationActivity";
	private ListView actualListView1 = null;
	private PullToRefreshListView xm_do_lv = null;
	private XMChildDocumentationAdapter mXMChildDocumentationAdapter = null;
	private Projects mProjects;
	private Context mContext;
	private int page = 1;
	private int scrollTopBottom = 0;// top,0;bottom,1
	// private View mMainData1View2Loading = null;
	private String Topdate = "";
	private String Bottomdate = "";
	private boolean overState = false;// 结束标志
	private boolean AddLock = false;// 网络锁
	private String user_id =""; 
	private String token ="";
	private int lastPos=0;
	private List<FileInfo> mFiles;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.xm_documentation);
		mContext = this;
		Process.setThreadPriority(-15);
		Intent intent = getIntent();
		if (intent == null) {
			Log.e(TAG, "intent is null");
			return;
		}
		overState = false;
		page = 1;
		
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
		user_id = prefs.getString(Contents.KEY_PERSONAL_LOGIN_USEID, ""); 
		token = prefs.getString(Contents.KEY_PERSONAL_LOGIN_TAKEN, "");

		if (intent.getExtras() != null) {
			mProjects = (Projects) intent.getExtras().getSerializable(
			"my_projects");
		}

		findViewById(R.id.xm_do_RelativeLayout_back).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						finish();
					}
				});

		xm_do_lv = (PullToRefreshListView) findViewById(R.id.xm_do_lv);
		xm_do_lv.setOnRefreshListener(new OnRefreshListener() {
			@SuppressLint("SimpleDateFormat")
			@Override
			public void onRefresh() {
				if (scrollTopBottom == 1) {
					if (!overState) {
						page++;
					}
					SimpleDateFormat sDateFormat = new SimpleDateFormat(
					"yyyy-MM-dd   hh:mm:ss");
					Topdate = sDateFormat.format(new java.util.Date());
					if (mProjects != null) {
						getDocumentationData(page);
					}
				} else if (scrollTopBottom == 0) {
					page = 1;
					overState = false;
					SimpleDateFormat sDateFormat = new SimpleDateFormat(
					"yyyy-MM-dd   hh:mm:ss");
					Bottomdate = sDateFormat.format(new java.util.Date());
					if (mProjects != null) {
						getDocumentationData(page);
					}
				}

			}
		});

		xm_do_lv.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				lastPos= xm_do_lv.getRefreshableView().getLastVisiblePosition();
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				int topbottom = xm_do_lv.getScollTopBottom();
				if (topbottom < 0) {
					scrollTopBottom = 0;
				} else {
					scrollTopBottom = 1;
				}
				Log.e("wop", " 档案    scrollTopBottom = " + scrollTopBottom);
				// if(xm_do_lv!=null){
				// xm_do_lv.onRefreshComplete();
				// }
				// if(!AddLock){
				// AddLock=true;
				// Log.e("wop"," 档案    firstVisibleItem = "+firstVisibleItem);
				// Log.e("wop"," 档案    visibleItemCount = "+visibleItemCount);
				// Log.e("wop"," 档案    totalItemCount = "+totalItemCount);
				// if(firstVisibleItem+visibleItemCount == totalItemCount){
				// scrollTopBottom=1;
				// if(xm_do_lv!=null){
				// xm_do_lv.setUpdatatime(Bottomdate);
				// }
				// }else if(firstVisibleItem == 0){
				// scrollTopBottom = 0;
				// if(xm_do_lv!=null){
				// xm_do_lv.setUpdatatime(Topdate);
				// }
				// }
				// Log.e("wop"," 档案    scrollTopBottom = "+scrollTopBottom);
				// }else{
				// AddLock=false;
				// }
			}
		});
		actualListView1 = xm_do_lv.getRefreshableView();
		if (mProjects != null) {
			getDocumentationData(page);
		}
		deleteFileOfDir(Network.cacheFilePath);
	}

	private void openDailog(String title, final String content) {
		new AlertDialog.Builder(mContext).setTitle(title).setMessage(content)
		.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				if (content != null && content.trim().equals("用户不存在")) {
					// finish();
				}
				if("登陆失效，需重新登陆".equals(content) || "join(f.username.errors)".equals(content)){
					LoginUtil.executeLoginFaild(mContext);
				}

			}
		}).show();
	}

	private void getDocumentationData(final int pageIndex) {
		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else {
			final ProgressDialog progressDialog = ProgressDialog.show(this,
					"网络数据", "...Loading...");
			// String URL =
			// "http://crmsoap.woniuwo.cn/project?project_id="+mProjects.getProject_id()
			// +"&user_id="+mProjects.getUser_id()+"&token="+mProjects.getToken()+
			// "&validation="+CRMUserBaseInfo.kValication
			// +"&part=members";
			String URL = Network.API_DOMAIN + "/data?project_id="
			+ mProjects.getProject_id() + "&user_id="
			+ user_id + "&token=" + token
			+ "&validation=" + CRMUserBaseInfo.kValication + "&page="
			+ pageIndex;
			// 文档资料接口：http://crmsoap.woniuwo.cn/data?project_id=
			// 536c3810d5ac70725f58643b
			// &user_id=3a2ca74f8b484303ade9b7e2655994d9
			// &token=f4d3335638c9411e98298222a7d2e54a
			// &validation=gAJ9cQAoVQZsb2NhbGVxAVUFemhfQ05xAl
			// &page=1
			// http://crmsoap.woniuwo.cn
			System.out.println("文档    URL  =  " + URL);
			// final ProgressDialog progressDialog = ProgressDialog.show(this,
			// "网络数据", "...Loading...");
			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
					Request.Method.GET, URL, null,
					new Response.Listener<JSONObject>() {
						@Override
						public void onResponse(JSONObject response) {
							ProgressDialogUtil.dissmis(progressDialog);
							System.out.println("文档 response=" + response);
							// if
							// (progressDialog.isShowing()&&progressDialog!=null)
							// {
							// progressDialog.dismiss();
							// }
							// try {
							// String
							// name=URLEncoder.encode(response.toString(),"gbk");
							// System.out.println("文档 name="+name);
							// } catch (UnsupportedEncodingException e1) {
							// // TODO Auto-generated catch block
							// e1.printStackTrace();
							// }
							try {
								// response={"data":[],"errors":[]}
								if (!response.isNull("data")) {
									String data = response.getString("data");
									if (data.equals("[]")) {
										overState = true;
										Toast.makeText(mContext, "已经到最后了~",
												Toast.LENGTH_SHORT).show();
									} else {
										org.json.JSONArray jsonArr;
										jsonArr = response.getJSONArray("data");
										if(mFiles==null || pageIndex==1){
											mFiles = new ArrayList<FileInfo>();
										}
										if (jsonArr.length() > 0) {
											for (int i = 0; i < jsonArr
											.length(); i++) {
												FileInfo mFile = new FileInfo();
												JSONObject jsonObj2 = jsonArr
												.getJSONObject(i);
												if (!jsonObj2.isNull("details")) {
													String details = jsonObj2
													.getString("details");
													mFile.setDetails(details);
												}
												if (!jsonObj2.isNull("files")) {
													String file = jsonObj2
													.getString("files");
													mFile.setFiles(file);
												}
												mFiles.add(mFile);
											}
										}
										mXMChildDocumentationAdapter = new XMChildDocumentationAdapter(
												XMChildDocumentationActivity.this,
												mFiles, mProjects);
										actualListView1
										.setAdapter(mXMChildDocumentationAdapter);
										if (pageIndex > 1) {
											actualListView1.setSelection(lastPos);
										}
									}
									if (xm_do_lv != null) {
										xm_do_lv.onRefreshComplete();
									}
								}
								if (!response.isNull("errors")) {
									String errors = response.get("errors")
									.toString();
									if (errors.equals("[]")) {
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response
											.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr
												.length(); i++) {
													JSONObject jsonObj2 = jsonArr
													.getJSONObject(i);
													if (!jsonObj2
															.isNull("desc")) {
														String desc = jsonObj2
														.getString("desc");
														mLoginError
														.setDesc(desc);
														openDailog("失败提示", desc);
													}
													if (!jsonObj2
															.isNull("value")) {
														String value = jsonObj2
														.getString("value");
														mLoginError
														.setValue(value);
													}
												}
											}
											// mCustomerContactInterface.setErrors(mLoginError);
										}
									}
								}
							} catch (NumberFormatException e) {
								if (progressDialog.isShowing()
										&& progressDialog != null) {
									progressDialog.dismiss();
								}
								e.printStackTrace();
							} catch (JSONException e) {
								if (progressDialog.isShowing()
										&& progressDialog != null) {
									progressDialog.dismiss();
								}
								e.printStackTrace();
							}
						}
					}, new Response.ErrorListener() {
						@Override
						public void onErrorResponse(VolleyError arg0) {
							ProgressDialogUtil.dissmis(progressDialog);
							System.out.println("sorry,Error");
						}
					});
			requestQueue.add(jsonObjectRequest);
		}
	}
	
	/**
	 * 删除缓存的文件
	 */
	private void deleteFileOfDir(String dirPath) {
		File fileDir=new File(dirPath);
		if(fileDir.exists()){
			File[] files=fileDir.listFiles();
			for(File file : files){
				file.delete();
			}
		}
	}
	


}

class XMChildDocumentationAdapter extends BaseAdapter {
	private List<FileInfo> Date = null;
	private Context context;
	private LayoutInflater mInflater;
	private Projects mProjects;
	final LruCache<String, Bitmap> lruCache = new LruCache<String, Bitmap>(
			15);
	private class GridHolder {
		LinearLayout LinearLayout1;
		ImageView imageView1;
		TextView xm_do_tv_item_title;
	}

	@SuppressLint("UseSparseArrays")
	public XMChildDocumentationAdapter(Context c, List<FileInfo> files,
			Projects mProjects) {
		super();
		this.context = c;
		this.Date = files;
		this.mProjects = mProjects;
		mInflater = (LayoutInflater) context
		.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
	}

	public int getCount() {
		return Date.size();
	}

	@Override
	public Object getItem(int index) {
		return Date.get(index);
	}

	@Override
	public long getItemId(int index) {
		return index;
	}

	@Override
	public View getView(final int index, View convertView, ViewGroup parent) {
		GridHolder holder;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.xm_documentation_item,
					null);
			holder = new GridHolder();
			holder.LinearLayout1 = (LinearLayout) convertView
			.findViewById(R.id.LinearLayout1);
			holder.xm_do_tv_item_title = (TextView) convertView
			.findViewById(R.id.xm_do_tv_item_title);
			holder.imageView1 = (ImageView) convertView
			.findViewById(R.id.imageView1);
			convertView.setTag(holder);
		} else {
			holder = (GridHolder) convertView.getTag();
		}

		String xm_title = Date.get(index).getFiles();
		xm_title = xm_title.substring(2, xm_title.length() - 2);
		holder.xm_do_tv_item_title.setText(xm_title);
		final String xm_con = Date.get(index).getDetails();
		// http://crm.woniuwo.cn/static/data/536c3810d5ac70725f58643b/得瑟得瑟.jpg

		// http://crm.woniuwo.cn/static/data/
		// 536c3810d5ac70725f58643b/%E5%98%8E%E5%98%8E%E5%98%8E%E5%98%8E.jpg
		// holder.imageView1.setText(xm_con);

		try {
			final String uris = Network.API_DOMAIN_FILE+"/static/data/"
				+ mProjects.getProject_id() + "/"
				+ java.net.URLEncoder.encode(xm_title,"utf-8");
			//Log.d("wop", "uris:   "+uris);
			final String uriss = uris.replaceAll("\\+", "%20");
//			final String uriss = URLEncoder.encode(uris,"gbk");
//			myFile = Uri.encode(myFile);

//			loadImageByVolley(uriss, holder.imageView1);
//			holder.imageView1.setBackgroundResource(R.drawable.jubaocrm_icon);
			// showImageByNetworkImageView(uris,holder.imageView1);

			holder.LinearLayout1.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					//Log.d("XMChildDocumentationAdapter", "uriss:"+uriss);
					new SubmitComAsyc(context,uriss).execute();
//				Uri  uri = Uri.parse(uris);
//				Intent  intent = new  Intent(Intent.ACTION_VIEW, uri);
//				context.startActivity(intent);
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
		return convertView;
	}

	/**
	 * 利用Volley异步加载图片
	 * 
	 * 注意方法参数: getImageListener(ImageView view, int defaultImageResId, int
	 * errorImageResId) 第一个参数:显示图片的ImageView 第二个参数:默认显示的图片资源 第三个参数:加载错误时显示的图片资源
	 */
	private void loadImageByVolley(String imageUrl, ImageView mImageView) {
		RequestQueue requestQueue = Volley.newRequestQueue(context);
		
		ImageCache imageCache = new ImageCache() {
			@Override
			public void putBitmap(String key, Bitmap value) {
//				value = compressImage(value);
				lruCache.put(key, value);
			}

			@Override
			public Bitmap getBitmap(String key) {
				return lruCache.get(key);
			}
		};
		ImageLoader imageLoader = new ImageLoader(requestQueue, imageCache);
		ImageListener listener = ImageLoader.getImageListener(mImageView,
				R.drawable.jubaocrm_icon, R.drawable.jubaocrm_icon);
		imageLoader.get(imageUrl, listener);
	}

	private Bitmap compressImage(Bitmap image) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 30, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 50;
		while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
			options -= 10;// 每次都减少10
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
		return bitmap;
	}
	
	
	//
	// /**
	// * 利用NetworkImageView显示网络图片
	// */
	// private void showImageByNetworkImageView(String imageUrl ,
	// NetworkImageView mImageView){
	// RequestQueue requestQueue = Volley.newRequestQueue(context);
	// final LruCache<String, Bitmap> lruCache = new LruCache<String,
	// Bitmap>(20);
	// ImageCache imageCache = new ImageCache() {
	// @Override
	// public void putBitmap(String key, Bitmap value) {
	// lruCache.put(key, value);
	// }
	//
	// @Override
	// public Bitmap getBitmap(String key) {
	// return lruCache.get(key);
	// }
	// };
	// ImageLoader imageLoader = new ImageLoader(requestQueue, imageCache);
	// mImageView.setTag("url");
	// mImageView.setImageUrl(imageUrl,imageLoader);
	// }
	
	ProgressDialog pd;
	class SubmitComAsyc extends AsyncTask<String, Void, String> {
		private Context context;
		private String fileUrl;
		private String filePath;
		private String fileExtName;
		public SubmitComAsyc(Context context,String fileUrl) {
			this.context = context;
			this.fileUrl=fileUrl;
			pd = new ProgressDialog(context);
			pd.setMessage("loading..");
			pd.setIndeterminate(true);
			pd.setCancelable(true);
			pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			pd.setButton("cancle", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					SubmitComAsyc.this.cancel(true);
				}
			});
			pd.show();
		}
		protected String doInBackground(String... arg) {
			InputStream is = null;
			FileOutputStream os = null;
			try {
				is = getInputStreamByUrl(fileUrl);
				File fileDir=new File(Network.cacheFilePath);
				if(!fileDir.exists()){
					fileDir.mkdirs();
				}
				filePath=Network.cacheFilePath+fileUrl.substring(fileUrl.lastIndexOf("/")+1);
				fileExtName=fileUrl.substring(fileUrl.lastIndexOf("."));
				File file=new File(filePath);
				file.createNewFile();
				os = new FileOutputStream(file);
				byte[] buf = new byte[1024];
				int len = 0;
				while ((len = is.read(buf)) != -1) {
					if(this.isCancelled()){
						break;
					}
					os.write(buf, 0, len);
				}
				os.flush();
			} catch (Exception e) {
				e.printStackTrace();
				return "fail";
			} finally {
				try {
					if (is != null)
						is.close();
					if (os != null)
						os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return "ok";
		}

		protected void onPostExecute(String value) {
			pd.dismiss();
//			Toast.makeText(context, value, Toast.LENGTH_SHORT).show();
			Intent intent = new Intent("android.intent.action.VIEW");
			Uri uri = Uri.fromFile(new File(filePath));
			intent.setDataAndType(uri, Network.mimeMap.get(fileExtName));
			try{
				context.startActivity(intent);
			}catch(ActivityNotFoundException e){
				openDailog(context,"网络提示","没有找到合适的打开程序");
			}
		}
	}
	private void openDailog(final Context mContext,String title, final String content) {
		new AlertDialog.Builder(mContext).setTitle(title)
		.setMessage(content).setPositiveButton("确定", null).show();
	}

	public static InputStream getInputStreamByUrl(String url) {
		HttpGet httpget = new HttpGet(url);
		HttpClient httpClient = new DefaultHttpClient();
		try {
//			httpget.setRequestProperty("User-agent", "Mozilla/4.0");
			httpClient.getParams().setParameter("http.socket.timeout", 30000);
			HttpResponse httpResponse = httpClient.execute(httpget);
			InputStream is = httpResponse.getEntity().getContent();
			return is;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
